package hello

import (
	"encoding/xml"
	"net/http"
	"appengine"
)

type Url struct {
	XMLName   xml.Name `xml:"url"`
	Location string `xml:"loc"`
}

type Urlset struct {
	XMLName   xml.Name `xml:"urlset"`
	NameSpace string `xml:"xmlns,attr"`
	Urls []*Url
}

func siteMapHandler(c *appengine.Context, w http.ResponseWriter, r *http.Request, params Params) string {
	w.Header().Set("Content-Type", "text/xml")

	set := &Urlset{NameSpace: "http://www.sitemaps.org/schemas/sitemap/0.9"}
	set.Urls = make([]*Url, 0)
	set.Urls = append(set.Urls, &Url{Location: "/"})
	set.Urls = append(set.Urls, &Url{Location: "/recipes"})
	categories := listAllCategories(c)
	// '/recipes?code=salaty'
	for i := 0; i < len(categories); i++ {
		set.Urls = append(set.Urls, &Url{Location: "/recipes?code=" + categories[i].Code})
	}
	// '/recipe?code=salat-bukovina'
	recipes := listAllRecipes(c, true)
	for i := 0; i< len(recipes); i++ {
		set.Urls = append(set.Urls, &Url{Location: "/recipe?code=" + recipes[i].Code})
	}
	b, err := xml.MarshalIndent(set, " ", " ")
	panicIfErr(err)
	w.Write(b)	
	return ""
}